﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;

namespace ClassRoomServer.Libs
{
    public class PowerpointConverter
    {
        public enum ImageFormat
        {
            JPG,
            PNG
        }

        public static int ConvertToImages(string pptFile, string imagesFolderLocation, ImageFormat imgFormat, int width, int height)
        {
            Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
            Presentation pptPresentation = pptApplication.Presentations.Open(pptFile,
                MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
            int totalImages = 0;
            try
            {               
                for (int i = 1; i <= pptPresentation.Slides.Count; i++)
                {
                    string imageFullName = imagesFolderLocation + "\\Slide" + i.ToString() + "." + imgFormat.ToString();
                    using (FileStream fs = new FileStream(imageFullName, FileMode.Create, FileAccess.ReadWrite))
                    {

                    }

                    pptPresentation.Slides[i].Export(imageFullName, imgFormat.ToString(), width, height);
                    totalImages++;
                }

                pptPresentation.Close();
                pptApplication.Quit();
                return totalImages;
            }
            catch
            {
                pptPresentation.Close();
                pptApplication.Quit();
                return totalImages;
            }
        }

        public static bool ConvertToPPTFromBytesArray(byte[] buffer, string saveLocation)
        {
            try
            {
                using (FileStream fs = new FileStream(saveLocation, FileMode.Create, FileAccess.ReadWrite))
                {
                    fs.Write(buffer, 0, buffer.Length);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool ConvertToPPTFromFileStream(FileStream fs, string saveLocation)
        {
            try
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);

                return ConvertToPPTFromBytesArray(buffer, saveLocation);
            }
            catch
            {
                return false;
            }
        }
    }
}
